<?php

/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not 
 *  exist, see <http://www.gnu.org/licenses/>.
 * 
 * $LastChangedDate: 2008-07-02 19:40:56 +0200 (Wed, 02 Jul 2008) $
 * $Rev: 1256 $
 * $Author: gavinspearhead $
 * $Id: admin_users.php 1256 2008-07-02 17:40:56Z gavinspearhead $
 */


define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);

$pathaau = realpath(dirname(__FILE__));

require_once "$pathaau/../functions/ajax_includes.php";
require_once "$pathaau/../functions/mail_functions.php";
if (!$isadmin)
	fatal_error($LN['error_noadmin']);

$prefs_root = load_config($db);
class users_c {
	public $username;
	public $fullname;
	public $email;
	public $password;
	public $admin;
	public $active;
	public $id;
	public $rights;
	function __construct ($id='', $u='', $fn='', $e='', $p='', $admin=0, $act=1, $r='c', $la=0)
	{
		global $LN;
		assert (is_numeric($id));
		$this->username = $u;
		$this->fullname = $fn;
		$this->email = $e;
		$this->password = $p;
		$this->admin = $admin;
		$this->active = $act;
		$this->id = $id;

        if ($this->fullname == '') 
            $this->fullname = '-';

		// Turn them into seperate variables for easy smartying:
		$rights = str_split(strtolower($r));
		$rightsarray = array();
		foreach($rights as $letter)
			$rightsarray[$letter] = 1;
		$this->rights = $rightsarray;
		if ($la != 0) 
			$this->last_active = readable_time(time() - $la, 'largest_long');
		else 	
			$this->last_active = $LN['never'];
	}
}


if (!isset($_REQUEST['cmd']))
	die_html('No command found');

$cmd = $_REQUEST['cmd'];
$id = isset($_REQUEST['id']) ?$_REQUEST['id']: FALSE ;
switch($cmd) {
case 'export_settings':
    header('Content-Type: text/html/force-download');
    header('Content-Disposition: attachment; filename=urd_users.xml');
    $xml = new urd_xml_writer('php://output');
    $xml->write_users($db);
    $users = get_all_userids($db);
    foreach($users as $u)
        $xml->write_user_settings($db, $u);
    $xml->output_xml_data();
    die;
    break;
case 'import_settings':
    if(isset ($_FILES['filename']['tmp_name'])) {
        try {
            $xml = new urd_xml_reader($_FILES['filename']['tmp_name']);
            $users = $xml->read_users($db);
            $settings = $xml->read_user_settings($db);
            if ($users != array()) {
                clear_all_users($db);
                set_all_users($db, $users, $settings);
                $prefs = $prefs_root;
                stop_urdd();
                usleep(500000);
                start_urdd(); 
                redirect('admin_users.php');
            }
        } catch (exception $e) {
            echo_debug_trace($e, 255);
        }

    } else 
        die_html('File not found');
    break;

case 'edit':
	if (is_numeric($id)) {
		$db->escape($id);
		$sql = " * FROM users WHERE \"ID\" = '$id'";
		$res = $db->select_query($sql, 1);
		if ($res === FALSE)
			die_html('User not found');
		$row = $res[0];

		$password = $row['pass'];
		$email = $row['email'];
		$name = $row['name'];
		$fullname = $row['fullname'];
		$id = $row['ID'];
		$rights = strstr(strtolower($row['rights']), 'c')?1:0;
		$autodownload = strstr(strtolower($row['rights']), 'a')?1:0;
		$post = strstr(strtolower($row['rights']), 'p')?1:0;
		$last_active = $row['last_active'];
		$isadmin = $row['isadmin'];
		$isactive = $row['active'];
	}else if ($id == 'new') {
        $password = '';
        $autodownload = '';
		$email = '';
		$name = '';
		$fullname ='' ;
		$rights = 0;
		$post = 0;
		$last_active = '';
		$isadmin = USER_USER;
		$isactive = USER_ACTIVE;

	} else {
		die_html('ID not found');
	}

	$smarty->assign('USER_ADMIN',	USER_ADMIN);
	$smarty->assign('USER_ACTIVE',	USER_ACTIVE);
	$smarty->assign('USER_PENDING',	USER_PENDING);
	$smarty->assign('id', $id );
	$smarty->assign('password', $password );
	$smarty->assign('email', $email );
	$smarty->assign('text_box_size', TEXT_BOX_SIZE);
	$smarty->assign('number_box_size', NUMBER_BOX_SIZE);
	$smarty->assign('name', $name );
	$smarty->assign('fullname', $fullname );
	$smarty->assign('rights', $rights );
	$smarty->assign('post', $post );
	$smarty->assign('isadmin', $isadmin);
	$smarty->assign('autodownload', $autodownload);
	$smarty->assign('isactive', $isactive );
	$smarty->assign('last_active', $last_active );
	$smarty->display('ajax_edit_users.tpl');
	die;
	break;
case 'resetpw':
	verify_challenge($_POST['challenge']);
	$newpw = generate_password(MIN_PASSWORD_LENGTH);
	$user_id = $id ;

	$db->escape($id, TRUE);
	$sql = "SELECT * FROM users WHERE \"ID\"=$id";
	$res = $db->execute_query($sql);
	if ($res === FALSE)
		die_html($LN['error_nosuchuser']);
	$email = $res[0]['email'];
	$fullname = $res[0]['fullname'];
	set_password($db, $user_id, $newpw, FALSE);
	try {
		mail_pw($db, $fullname, $email, $newpw, get_config($db, 'admin_email'));
	} catch (exception $e) {
		write_log('Could not send email message', LOG_WARNING);
		die_html('Password reset, but could not send email: ' . $e->getmessage());
	}
	echo 'OK';
	die;
	break;
case 'delete':
	verify_challenge($_POST['challenge']);
	delete_user($db, $id);
	echo 'OK';
	die;
	break;
case 'update_user':
    verify_challenge($_POST['challenge']);
	$rights = '';
	$fullname = $_POST['fullname'];
	$username = $_POST['username'];
	$password = $_POST['password'];
	$email = $_POST['email'];
	if ($_POST['isadmin'] == 'on')
		$isadmin = USER_ADMIN;
	else 
		$isadmin = USER_USER;
	if ($_POST['isactive'] == 'on')
		$active = USER_ACTIVE;
	else 
		$active = USER_INACTIVE;
	if ($_POST['seteditor'] == 'on')
		$rights .= 'C';

	if ($_POST['post'] == 'on')
		$rights .= 'P';
	if ($_POST['autodownload'] == 'on')
		$rights .= 'A';
	if (is_numeric($id)) {
		$db->escape($id);
		$sql = " \"ID\", \"active\" FROM users WHERE \"ID\" = '$id'";
		$res = $db->select_query($sql, 1);
		if ($res === FALSE)
			die_html('User not found');
		try {
			update_user($db, $id, $username, $fullname, $email, $isadmin, $active, $rights);
		} catch (exception $e) {
			die_html ($e->getMessage());
		}
		$email_allowed = get_config($db, 'sendmail');
		if ($email_allowed) {
			try {
				if ($res[0]['active'] != $active) // we only send an message if the active status changed.
					mail_user_update($db, $username, $fullname, $email, $isadmin, $active, $prefs_root['admin_email']);
			} catch (exception $e) {
				die_html('User updated, but could not send email: ' . $e->getmessage());
			}
		}
	} elseif ($id == 'new') {
		$username_db = $username;
		$db->escape($username_db, FALSE);
		$query = "SELECT \"ID\" FROM users WHERE \"name\"='$username_db'";
		$res = $db->execute_query($query);
		if ($res === FALSE) {
			try {
				add_user($db, $username, $fullname, $email, $password, $isadmin, $active, $rights);
			} catch (exception $e) {
				die_html ($e->getMessage());
			}
		} else 
			die_html($LN['error_userexists']. ' ' . $username);
	}
	else 
		die_html('Unknown ID');
	echo 'OK';
	die;
	break;
case 'reload_users':
    $sort = get_request('sort', 'name');
    $sort_dir = get_request('sort_dir', 'asc');

    if (!in_array($sort, array('name', 'fullname', 'email', 'rights', 'last_active', 'isadmin', 'active')))
        fatal_error('invalid sortname');
    if (!in_array($sort_dir, array('asc', 'desc')))
        fatal_error('invalid sortname');

	// Display:
	$sql = "SELECT * FROM users WHERE \"ID\">0 ORDER BY \"$sort\" $sort_dir";
	$res = $db->execute_query($sql);
	foreach ($res as $row) {
		$password = $row['pass'];
		$email = $row['email'];
		$name = $row['name'];
		$fullname = $row['fullname'];
		$id = $row['ID'];
		$rights = strtolower($row['rights']);
		$last_active = $row['last_active'];
		$users[] = new users_c($id, $name, $fullname, $email, $password, $row['isadmin'], $row['active'], $rights, $last_active);
	}
	$challenge = set_challenge();
    $email_allowed = get_config($db, 'sendmail');

	$smarty->assign('USER_ADMIN',	USER_ADMIN);
	$smarty->assign('USER_ACTIVE',	USER_ACTIVE);
	$smarty->assign('USER_PENDING',	USER_PENDING);
    $smarty->assign('order',	    $sort);
    $smarty->assign('order_dir',	$sort_dir);
	$smarty->assign('users',	    $users);
	$smarty->assign('emailallowed',	$email_allowed);
	$smarty->assign('challenge',	$challenge);
	$smarty->assign('maxstrlen',	$prefs['maxsetname']/3);
	$smarty->display('ajax_admin_users.tpl');
	die;
default:
	die_html ("O-oh - Unknown command $cmd");
	break;
}

echo 'OK';
?>
